package com.ctg.behavior.calc.impala.calculator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.api.CtCalcStatus;
import com.ctg.behavior.calc.common.CtSQLParam;
import com.ctg.behavior.calc.impala.CtCalculator;
import com.ctg.behavior.calc.impala.builder.usergroups.CtUGCalcResultBuilder;
import com.ctg.behavior.calc.impala.engine.ImpalaSQLEngine;
import com.ctg.behavior.calc.impala.transfer.usergroups.CtUGTransfer;
import com.ctg.behavior.calc.impala.utils.CtCalculatorUtils;
import com.ctg.behavior.client.impala.common.CtQueryResult;
import com.ctg.behavior.common.calc.CtCalcBody;
import com.ctg.behavior.common.calc.CtCalcResult;
import com.ctg.behavior.common.usergroups.CtUGCalcBody;
import com.ctg.behavior.common.usergroups.CtUGCalcResult;
import com.ctg.behavior.utils.CtDateUtils;
import com.ctg.behavior.utils.CtStatusUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtUGCalculator implements CtCalculator {

	@Autowired
	private ImpalaSQLEngine sqlEngine;
	@Autowired
	private CtUGTransfer ugTransfer;
	@Autowired
	private CtUGCalcResultBuilder calcResultBuilder;

	/****************************************************************
	 * @apiNote: 1.
	 * @apiNote: 2.
	 */
	@Override
	public CtCalcResult doCalculator(CtCalcBody calcBody) {

		CtUGCalcResult calcResult = new CtUGCalcResult();

		if (!(calcBody instanceof CtUGCalcBody)) {
			log.error("calcBody={}", calcBody.getClass());
			CtStatusUtils.fillStatus(calcResult, CtCalcStatus.BodyNoMatch);
			return calcResult;
		}

		CtUGCalcBody ugCalcBody = (CtUGCalcBody) calcBody;
		log.info("calcBody: {}", JSON.toJSONString(calcBody));

		String impalaSQL = ugTransfer.doTransfer(ugCalcBody, new CtSQLParam());
		log.info("impalaSQL={}", impalaSQL);

		String queryType = "UserGroup";

		log.info("time - start: {}", CtDateUtils.getCurrentDateSSS());
		CtQueryResult queryResult = sqlEngine.doQuery(queryType, impalaSQL);
		log.info("queryResults={}", JSON.toJSONString(queryResult));
		log.info("time - end: {}", CtDateUtils.getCurrentDateSSS());

		CtCalculatorUtils.fillCalcResult(calcResult, queryResult);
		if (!calcResult.getSuccess()) {
			log.error(queryResult.getCode());
		}

		calcResult = calcResultBuilder.doBuilder(calcResult, queryResult.getRows(), ugCalcBody);
		log.info("calcResult={}", JSON.toJSONString(calcResult));
		
		return calcResult;
	}

}
